package com.hyg.module_third_party_demo.litepal;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.os.AsyncTask;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.hyg.module_third_party_demo.litepal.DataModule.Option;
import com.hyg.module_third_party_demo.litepal.DataModule.Relevance;
import com.hyg.module_third_party_demo.litepal.DataModule.Subject;
import com.hyg.module_third_party_demo.litepal.DataModule.Symptom;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class DataBaseHelper {

    public static final String DataBaseInfo="databaseInfo";
    public static final String DataBaseVersion="databaseVersion";
    public static final String DataBaseDir="testtingquestions";
    Context context;
    public static final String TAG = "lgb";
    DataBaseUpdateLisenner lisenner;

    public DataBaseHelper(Context context) {
        this.context = context;
    }

    /**
     * @description 检查数据库版本
     * @param 
     * @return     true 需要升级  ，false 版本相同
     * @author visitant
     * @time 2020/11/5 10:35
     */
    public boolean checkVersion() {
        String[] files;
        try {
            files = context.getResources().getAssets().list(DataBaseDir);
            for (int i = 0; i < files.length; i++) {
                int index_name = files[i].lastIndexOf("_");
                int index_version = files[i].lastIndexOf(".");
                String fileVersion = files[i].substring(index_name + 1, index_version);
                String fileName = files[i].substring(0, index_name);
                SharedPreferences preferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
                if (!preferences.getString(DataBaseVersion, "").equalsIgnoreCase(fileVersion)) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    /**
     * @description 异步更新数据库
     * @param 
     * @return 
     * @author visitant
     * @time 2020/11/5 10:36
     */
    public void updateDataBase(DataBaseUpdateLisenner lisenner) {
        this.lisenner = lisenner;
        new ReadTxtTask().execute();
    }

    
    private class ReadTxtTask extends AsyncTask<Void, Void, String> {
        @Override
        protected void onPreExecute() {
            if (lisenner != null) {
                lisenner.onStart();
            }
        }

        @Override
        protected String doInBackground(Void... params) {
            AssetManager manager = context.getResources().getAssets();
            String fileVersion;
            String fileName = "";
            try {
                String[] files = context.getResources().getAssets().list(DataBaseDir);
                for (int i = 0; i < files.length; i++) {
                    int index_name = files[i].lastIndexOf("_");
                    int index_version = files[i].lastIndexOf(".");
                    fileVersion = files[i].substring(index_name + 1, index_version);
                    fileName = files[i].substring(0, index_name);
                    InputStream inputStream = manager.open(DataBaseDir + "/" + files[i]);
                    InputStreamReader isr = new InputStreamReader(inputStream,
                            "UTF-8");
                    BufferedReader br = new BufferedReader(isr);
                    StringBuilder sb = new StringBuilder();
                    String length;
                    while ((length = br.readLine()) != null) {
                        sb.append(length + "\n");
                    }
                    br.close();
                    isr.close();
                    inputStream.close();
                    boolean saveResult = saveDataBaseInfo(fileName, sb.toString());             //文件转换位数据库文件
                    if (saveResult) {
                        setShareString(fileName,DataBaseVersion, fileVersion);        //本地保存数据库版本
                    } else if (lisenner != null) {
                        lisenner.onFail(fileName);
                    }
                }
                if (lisenner != null) {
                    lisenner.onSuccess();
                }
                return "";
            } catch (IOException e) {
                e.printStackTrace();
                if (lisenner != null) {
                    lisenner.onFail(fileName);
                }
            }
            return "";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

        }
    }


    public void setShareString(String fileName, String key, String value) {
        SharedPreferences.Editor editor = context.getSharedPreferences(fileName, Context.MODE_PRIVATE).edit();
        editor.putString(key, value);
        editor.apply();
    }

    /**
     * @description 数据库实体存储到LitePal数据库
     * @param 
     * @return 
     * @author visitant
     * @time 2020/11/5 10:39
     */
    public boolean saveDataBaseInfo(String fileName, String dataString) {
        boolean result = false;
        switch (fileName) {
            case "option":
                ArrayList<Option> OptionList = (ArrayList<Option>) JSONArray.parseArray(JSON.parseObject(dataString).getString("data"), Option.class);
                for (int i = 0; i < OptionList.size(); i++) {
                    result = OptionList.get(i).save();
                }
//                LitePal.saveAll(OptionList);
                break;
            case "relevance":
                ArrayList<Relevance> RelevanceList = (ArrayList<Relevance>) JSONArray.parseArray(JSON.parseObject(dataString).getString("data"), Relevance.class);
                for (int i = 0; i < RelevanceList.size(); i++) {
                    result = RelevanceList.get(i).save();
                }
//                LitePal.saveAll(RelevanceList);
                break;
            case "subject":
                ArrayList<Subject> SubjectList = (ArrayList<Subject>) JSONArray.parseArray(JSON.parseObject(dataString).getString("data"), Subject.class);
                for (int i = 0; i < SubjectList.size(); i++) {
                    result = SubjectList.get(i).save();
                }
//                LitePal.saveAll(SubjectList);
                break;
            case "symptom":
                ArrayList<Symptom> SymptomList = (ArrayList<Symptom>) JSONArray.parseArray(JSON.parseObject(dataString).getString("data"), Symptom.class);
                for (int i = 0; i < SymptomList.size(); i++) {
                    result = SymptomList.get(i).save();
                }
//                LitePal.saveAll(SymptomList);
                break;
        }
        return result;
    }

}
